import datetime
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.houses.models import House
from apps.orders.models import Order
from utils.response_code import RET


class OrdersView(View):
    def get(self, request):
        """
        获取订单列表
        角色类型：【custom: 房客，landlord：房东】 查询字符串
        :param request:
        :return:
        """
        # user = None
        # user.id = 3
        # 判断是否登录
        # user = request.user
        # if not user.is_authenticated:
        #     return JsonResponse({'code': 400, 'errmsg': '请登录'})

        role = request.GET.get('role')

        if not role:
            return JsonResponse({'code':RET.PARAMERR, 'errmsg':'缺少role参数'})

        if role not in ['custom', 'landlord']:
            return JsonResponse({'code':RET.PARAMERR, 'errmsg':'role参数错误'})

        # 先查询出所有订单数据 并且按照最新时间排序
        order_list = []
        orders  = None
        # 房客
        if role == 'custom':
            # orders = Order.objects.filter(user_id=3).order_by('-create_time')
            orders = Order.objects.filter(user=request.user).order_by('-create_time')
            # 根据访客用户id查询出他的订单
            # for order in orders:
            #     order_list.append({
            #         "amount": order.amount,
            #         "comment": order.comment,
            #         "ctime": order.create_time,
            #         "days": order.days,
            #         "end_date": order.end_date,
            #         "img_url": order.house.index_image_url,
            #         "order_id": order.id,
            #         "start_date": order.begin_date,
            #         "status": order.ORDER_STATUS_ENUM[order.status],
            #         "title": order.house.title  # 通过外键关联查询 该用户订单下租房的标题
            #     })

        # 房东
        elif role=='landlord':
            # 房东所有的订单
            # house = request.user.houses.all()  # 房东所有的房子
            # orders = Order.objects.filter(house=house).order_by('-create_time')
            # 1.房东查询所拥有的房子
            houses=House.objects.filter(user_id = request.user.id)
            house_ids=[ house.id for house in houses] # 所有的房子id列表
            orders=Order.objects.filter(house_id__in=house_ids)

            # for order in orders:
            #     order_list.append({
            #         "amount": order.amount,
            #         "comment": order.comment,
            #         "ctime": order.create_time,
            #         "days": order.days,
            #         "end_date": order.end_date,
            #         "img_url": order.house.index_image_url,
            #         "order_id": order.id,
            #         "start_date": order.begin_date,
            #         "status": order.ORDER_STATUS_ENUM[order.status],
            #         "name": user.realname
            #     })
        # else:
        #     return JsonResponse({'code':400, 'errmsg':'用户未登录错误'})

        for order in orders:
            order_list.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": order.house.index_image_url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": order.ORDER_STATUS_ENUM[order.status],
                "title": order.house.title  # 通过外键关联查询 该用户订单下租房的标题
            })

        data = {
            'orders': order_list
        }
        return JsonResponse({'errno': RET.OK, "errmsg": '获取订单列表成功', 'data': data})

    def post(self, request):
        """
        添加订单
        1.接受参数
        2.校验参数
        3.数据库增删改查
        4.返回结果
        :param request:
        :return:
        """
        # 判断是否登录
        # if not request.user.is_authenticated:
        #     return JsonResponse({'code': 400, 'errmsg': '请登录'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date_str = json_dict.get('start_date')
        end_date_str = json_dict.get('end_date')  # str表示是字符串类型的日期

        if not all([house_id, start_date_str, end_date_str]):
            return JsonResponse({'code': RET.PARAMERR, 'errmsg': '缺少参数错误'})

        start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d').date()
        end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d').date()
        # assert 条件成立继续往下执行 不成立则报错
        # assert start_date_str < end_date_str, Exception('错误:开始日期大于结束日期')
        # days =

        # 检验end_date： 如果结束入住日期小于开始入住日期，　用户选择有误，　返回错误
        if end_date < start_date:
            return JsonResponse({'code': RET.PARAMERR, 'errmsg': '参数end_date有误'})

        # 判断house_id是否合法 房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            # logger.error(e)
            return JsonResponse({'code': RET.PARAMERR, 'errmsg': 'house_id参数错误'})

        # 检验start_date: 如果开始入住日期小于当前的日期， 参数错误，返回错误
        # if start_date < datetime.date.today():
        #     return JsonResponse({'code': 400, 'errmsg': '参数start_date有误'})

        # 自己不能订购自己发布的房间
        if request.user.id == house.user.id:
            return JsonResponse({'code': RET.ROLEERR, 'errmsg': '自己不能订购自己发布的房间'})

        # 判断房间当前是否有他人已经预定  符合条件的个数大于1则已被其他人预定
        try:
            count = Order.objects.filter(house=house, begin_date__lt=end_date, end_date__gt=start_date).count()
        except:
            return JsonResponse({'code': RET.DBERR, 'errmsg': '预定日期查询错误'})
        if count > 0:
            return JsonResponse({'code': RET.DATAERR, 'errmsg': '房间已被预定'})

        # 创建订单基本信息 根据房屋id创建订单id并返回
        try:
            order = Order.objects.create(
                # user_id=3,  # 暂时已用户id=3的展示
                user_id=request.user,
                # user_id=3 # 测试,
                house_id=house_id,  # 租房id
                begin_date=start_date_str,  # 开始日期
                end_date=end_date_str,  # 截止日期
                days=(end_date - start_date).days,  # 租房时长
                # days=1,  # 租房时长
                house_price=house.price,  # 租房单价
                amount=house.price * (end_date - start_date).days,  # 总金额
                # status=Order.ORDER_STATUS_ENUM[Order.status]  # 修改订单状态
            )
        except:
            return JsonResponse({'code':RET.DBERR, 'errmsg':'创建订单错误'})

        # 返回生成的订单id
        data = {'order_id': order.id}
        return JsonResponse({'code': RET.OK, 'errmsg': '下单成功', 'data': data})


"""
{
    "data": {
        "order_id": 1
    },
    "errno": "0",
    "errmsg": "下单成功"
}
"""


class OrdersStatusView(View):
    """
    接单和拒单 单个订单
    操作类型：【accept: 接单，reject：拒单】
    拒单原因，如果是拒单时需要传入
    """

    def put(self, request, order_id):
        #     if not request.user.is_authenticated:
        #         return JsonResponse({'code': 400, 'errmsg': '请登录'})

        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        # 参数校验
        if action not in ("accept", "reject"):
            return JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        try:
            order = Order.objects.get(id=order_id)
            # order = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS["WAIT_ACCEPT"]).first()

        except:
            return JsonResponse({'code': 400, 'errmsg': 'order_id参数错误'})

        if action == 'accept':
            # 接单
            order.status = order.ORDER_STATUS['WAIT_COMMENT']  # 修改状态 接单状态码3 待评价

        else:
            # 拒单
            reason = json_dict.get('reason')
            order.comment = reason  # 修改拒单原因
            order.status = order.ORDER_STATUS['REJECTED']  # 修改状态 拒单状态码6

        try:
            order.save()
        except:
            return JsonResponse({'code':RET.DBERR, 'errmsg':'保存订单状态错误'})

        return JsonResponse({'code': RET.OK, 'errmsg': '操作成功'})


class OrdersCommentView(View):
    """
    评价订单
    """

    def get(self, request):
        """
        显示
        :param request:
        :return:
        """
        pass

    def put(self, request, order_id):  # 路径参数
        # if not request.user.is_authenticated:
        #     return JsonResponse({'code': 400, 'errmsg': '请登录'})

        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')  # 评价

        if not comment:
            return JsonResponse({"code": RET.PARAMERR, "errmsg": "请输入评论内容"})

        try:  # 要评论的 订单id
            order = Order.objects.get(id=order_id)
        except:
            return JsonResponse({'code': RET.PARAMERR, 'errmsg': 'order_id参数错误'})

        try:
            order.house.order_count += 1
            order.status = Order.ORDER_STATUS["COMPLETE"]
            order.comment = comment  # 更新评论
            order.save()
        except:
            return JsonResponse({'code': RET.DBERR, 'errmsg': '更新评论错误'})


        return JsonResponse({'code': RET.OK, 'errmsg': '评论成功'})

# Create your views here.\

